# encoding: UTF-8
import sys
from PyQt4.QtGui import *
from PyQt4.QtSql import *

class TradeAccountManage(QWidget):
    def __init__(self,path,parent=None):

        QWidget.__init__(self, parent)
        self.resize(700,200)
        self.setWindowTitle(u"管理交易账号")
        self.path = path
        self.db = None


        self.view = QTableView()
        self.initDb()
        layout = QVBoxLayout(self)
        layout.addWidget(self.view)

        btnLayout = QHBoxLayout(self)
        btnLayout.addStretch(1)
        addBtn = QPushButton(u"添加交易账号")
        addBtn.clicked.connect(self.onAdd)
        btnLayout.addWidget(addBtn)

        closeBtn = QPushButton(u"关闭")
        closeBtn.clicked.connect(self.onClose)
        btnLayout.addWidget(closeBtn)

        layout.addLayout(btnLayout)
        self.setLayout(layout)


    def createTable(self):
        query = QSqlQuery(self.db)
        query.exec_(
            '''
            CREATE TABLE IF NOT EXISTS "trade_account" (
              "id" INTEGER PRIMARY KEY AUTOINCREMENT,
              "broker" varchar(64) NOT NULL,
              "broker_account" varchar(128) NOT NULL,
              "broker_pass" varchar(128) NOT NULL,
              "broker_name" varchar(128) DEFAULT NULL,
              "broker_extra" TEXT DEFAULT NULL
            );
           '''
        )


    def initDb(self):

        if self.db:
            self.closeDatabase()

        self.db = QSqlDatabase.addDatabase("QSQLITE", "db1")
        self.db.setDatabaseName(self.path)
        if not self.db.open("", ""):
            QMessageBox.warning(self, "PyQT", u"链接数据库失败", QMessageBox.Yes, QMessageBox.No)
            return None
        self.createTable()
        self.model = QSqlTableModel(None, self.db)
        self.model.setTable("trade_account")
        self.model.select()

        self.view.setModel(self.model)


    def onAdd(self):
        rowPosition = self.model.rowCount()
        self.model.insertRow(rowPosition)




    def closeDatabase(self):

        self.view.setModel(None)
        del self.model
        self.db.close()
        del self.db
        QSqlDatabase.removeDatabase("db1")

    def onClose(self):

        self.closeDatabase()
        self.close()


if __name__ == "__main__":

    app = QApplication(sys.argv)


    window = TradeAccountManage("C:/Users/jacob/test2.db")
    window.show()
    sys.exit(app.exec_())